#include "custompushbutton.h"
#include <QDebug>
#include "uicommon.h"

CustomPushButton::CustomPushButton(QWidget *parent)
    : QPushButton(parent)
{

}

CustomPushButton::CustomPushButton(QString &text, QWidget *parent)
    : QPushButton(text, parent), m_fullText(text)
{

}

void CustomPushButton::setText(const QString &text)
{
    setFullText(text);
}

void CustomPushButton::setFullText(const QString &text)
{
    m_fullText = text;
    update();
}

void CustomPushButton::setTextLimitShrink(const QString &text, int width)
{
    this->setMinimumWidth(qMin(this->fontMetrics().width(text), width));
    setFullText(text);
}

void CustomPushButton::setTextLimitExpand(const QString &text)
{
    int textWidth = this->fontMetrics().width(text);
    this->setMaximumWidth(textWidth);
    setFullText(text);
}

QString CustomPushButton::fullText() const
{
    return m_fullText;
}

void CustomPushButton::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event);
    elideText();
}

void CustomPushButton::elideText()
{
    QFontMetrics fm = this->fontMetrics();
    int dif = fm.width(m_fullText) - this->width();
    // 新版主题框架在相等的时候也会有显示不全的问题
    if (dif >= 0) {
        // 当dif==0时依然会显示不全，-5保证控件文字可以显示完全
        QString showText = fm.elidedText(m_fullText, Qt::ElideRight, this->width()-5);

        QPushButton::setText(showText);
        if (showText != m_fullText) {
            QString str = dealMessage(m_fullText);
            this->setToolTip(str);
        } else {
            this->setToolTip("");
        }
    } else {
        QPushButton::setText(m_fullText);
        this->setToolTip("");
    }
}
